//
//  EFengShareDetailController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/3/22.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengShareDetailController.h"
#import "EFengShare.h"
#import "EFengShareFrame.h"
#import "CShareMgr.h"
#import "CShareCommentMgr.h"
#import "EFengContent.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "EFengShareCommentToolBar.h"
#import "EFengShareEmotionView.h"
#import "EFengShareCell.h"
#import "EFengPersonalShareController.h"
#import "RIButtonItem.h"
#import "UIActionSheet+Blocks.h"
#import "CXmppRequestMgr.h"
#import "UIUtil.h"
#import "CFolderMgr.h"
#import "JKAlertDialog.h"
#import "CSharePersonMgr.h"
#import "EFengShareController.h"
#import "EFRootViewController.h"
@interface EFengShareDetailController ()<UITableViewDataSource, UITableViewDelegate, EFengShareCommentToolBarDelegate, EFengShareCellDelegate>

StrongProperty CShareCommentMgr *commentMgr;
StrongProperty CShareMgr *shareMgr;
StrongProperty UITableView *tableView;
StrongProperty CContactModel *curContact;
StrongProperty CContactMgr *conMgr;
StrongProperty NSMutableArray *dataArray;
StrongProperty EFengContent *shareComment;
StrongProperty CSharePersonMgr *personMgr;

@end

@implementation EFengShareDetailController

#pragma mark 懒加载

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (CContactModel *)curContact
{
    if (_curContact == nil) {
        _curContact = [self.conMgr loadCurContact];
    }
    return _curContact;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = CommonColor;
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    self.navigationItem.title = @"分享详情";
    
    self.shareMgr = [[CShareMgr alloc] init];
    self.personMgr = [[CSharePersonMgr alloc] init];
    self.commentMgr = [[CShareCommentMgr alloc] init];
    self.conMgr = [[CContactMgr alloc] init];
    
    CContactModel *curContact = [self.conMgr loadCurContact];
    EFengShare *share = [self.shareMgr getShareWithShareId:self.shareId];
    EFengShareFrame *shareFrame = [[EFengShareFrame alloc] init];
    share.contentReply = [self.commentMgr getShareCommentWithShareId:share.shareId];
    share.isZan = [self.commentMgr isHasZanIdWithShareId:share.shareId userId:curContact.UserID];
    share.praiseArray = [self.commentMgr getSharePraiseWithShareId:share.shareId];
    if ([curContact.UserID isEqualToString:share.releaseUserId]) {
        share.isShowShanchu = YES;
    } else {
        share.isShowShanchu = NO;
    }
    
    shareFrame.share = share;
    [self.dataArray addObject:shareFrame];
    
    self.tableView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f);
    [self.view addSubview:self.tableView];
    
    
    //增加下拉刷新
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)];
    [self.view addGestureRecognizer:tap];
    
}



-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }
    
    self.tableView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f);
    
    EFengShareCommentToolBar *tool = [EFengShareCommentToolBar defaultShareCommentToolBar];
    
    tool.eFengShareCommentToolBarDelegate = self;
    CGRect fr = tool.frame;
    fr.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
    tool.frame = fr;
    [self.view addSubview:tool];
    
    
    EFengShareEmotionView *emo = [EFengShareEmotionView defaultShareEmotionView];
    [self.view addSubview:emo];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    EFengShareCommentToolBar *tool = [EFengShareCommentToolBar defaultShareCommentToolBar];
    tool.eFengShareCommentToolBarDelegate = nil;
    [tool removeFromSuperview];
    
    [[EFengShareEmotionView defaultShareEmotionView] removeFromSuperview];
    
}


- (void)loadNewData
{
    EFengShareFrame *obj = self.dataArray.lastObject;
    EFengShare *share = obj.share;
    share.contentReply = [self.commentMgr getShareCommentWithShareId:obj.share.shareId];
    share.isZan = [self.commentMgr isHasZanIdWithShareId:obj.share.shareId userId:self.curContact.UserID];
    share.praiseArray = [self.commentMgr getSharePraiseWithShareId:share.shareId];
    if ([self.curContact.UserID isEqualToString:obj.share.releaseUserId]) {
       share.isShowShanchu = YES;
    } else {
        share.isShowShanchu = NO;
    }
    
    obj.share = share;
    [self.tableView reloadData];
}


#pragma mark tableView代理以及数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EFengShareFrame *shareFrame = self.dataArray.lastObject;
    return shareFrame.cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EFengShareFrame *shareFrame = self.dataArray.lastObject;
    EFengShareCell *cell = [EFengShareCell eFengShaeCellWithTableView:tableView];
    cell.cellIndexPath = indexPath;
    cell.eFengShareCellDelegate = self;
    cell.shareFrame = shareFrame;
    
    return cell;
}


- (void)eFengShareCellDidClickHeadWithShare:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{
    [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
   
    
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    nav.navigationBarHidden = NO;
    self.navigationController.navigationBarHidden = YES;
    
    EFengPersonalShareController *per = [[EFengPersonalShareController alloc] init];
    per.userId = share.share.releaseUserId;
    
    [nav pushViewController:per animated:YES];
}
//bug 9130 fix by lixu
- (void)eFengShareCellDidClickHuiFuWithShare:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{

    EFengShareCommentToolBar *toolBar = [EFengShareCommentToolBar defaultShareCommentToolBar];
    if ([toolBar.contentText isFirstResponder] || !toolBar.isEmotionShow) {
        [toolBar resetToolPositionToInitial];
        
    } else {
        [toolBar.contentText becomeFirstResponder];
        toolBar.contentText.text = @"";
        toolBar.contentText.placeholder = @"回复...";
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:inedexPath];
        CGPoint pt = self.tableView.contentOffset;
        CGFloat cellHeit = CGRectGetMaxY(cell.frame) - pt.y;
        if (cellHeit > toolBar.y) {
            
            
            pt.y = pt.y + cellHeit - toolBar.y;
            [self.tableView setContentOffset:pt animated:NO];
            
            
        } else {
            
            
        }
    }
    
}

- (void)eFengshareCommentsViewDidHuifuWithComment:(EFengContent *)comment share:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{
    self.shareComment = comment;
    EFengShareCommentToolBar *toolBar = [EFengShareCommentToolBar defaultShareCommentToolBar];
    if ([comment.sendUserId isEqualToString:self.curContact.UserID]) {
        
        if ([toolBar.contentText isFirstResponder] || !toolBar.isEmotionShow) {
            [toolBar resetToolPositionToInitial];
            
        }
        
        
        RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消" action:^{
            
        }];
        
        __block EFengShareDetailController *block = self;
        
        RIButtonItem *selectItem = [RIButtonItem itemWithLabel:@"删除" action:^{
                [block.commentMgr updateShareCommentIsUnNetCompletedWithComment:comment isDel:YES];
                [[CXmppRequestMgr shareInstance] cancelPraiseShareWithCommentId:comment.commentId date:comment.date successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                    
                    if ([responseObject[@"result"] isEqualToString:@"success"]) {
                        
                        [block.commentMgr delShareCommentWithCommentId:comment.commentId];
                    }
                    
                } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                    
                }];
            [self loadNewData];
        }];
        
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil cancelButtonItem:cancelItem destructiveButtonItem:nil otherButtonItems:selectItem, nil];
        [actionSheet showInView:self.view];
        
        
    } else {
        if ([toolBar.contentText isFirstResponder] || !toolBar.isEmotionShow) {
            [toolBar resetToolPositionToInitial];
            
        } else {
            [toolBar.contentText becomeFirstResponder];
            [toolBar.contentText setText:@""];
            [toolBar.contentText setPlaceholder:[NSString stringWithFormat:@"回复%@...",comment.sendUserName]];
           
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:inedexPath];
            CGPoint pt = self.tableView.contentOffset;
            CGFloat cellHeit = CGRectGetMaxY(cell.frame) - pt.y;
            if (cellHeit > toolBar.y) {
                pt.y = pt.y + cellHeit - toolBar.y;
                [self.tableView setContentOffset:pt animated:NO];
            }
        }
    }
    
}
- (void)eFengShareCellDidClickShanChuWithShare:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{
    __weak EFengShareDetailController *block = self;
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"确定要删除该分享内容?"];
    [alert addButton:Button_OK withTitle:@"是" handler:^(JKAlertDialogItem *item) {
        
        [self.shareMgr updateShareIsUnNetCompletedWithShare:share.share isDel:YES];
        [block.personMgr delShareWithShareId:share.share.shareId];
        [[CXmppRequestMgr shareInstance] delShareWithDate:share.share.date shareId:share.share.shareId successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ([responseObject[@"result"] isEqualToString:@"success"]) {
                [block.shareMgr delShareWithShareId:share.share.shareId];
            }
            
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
        [block.dataArray removeAllObjects];
        [block.tableView reloadData];
        //bug 9477 fixed by lixu
        NSArray *array = self.navigationController.viewControllers;
        for (UIViewController *controller in array) {
            if ([controller isKindOfClass:[EFRootViewController class]]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    }];
    
    [alert addButton:Button_CANCEL withTitle:@"否" handler:^(JKAlertDialogItem *item) {
        
        
    }];
    [alert show];

    
}
- (void)eFengShareCellDidClickZanWithShare:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{
    if (share.share.isZan) {
        EFengContent *comment = [self.commentMgr getZanIdWithShareId:share.share.shareId userId:self.curContact.UserID];
        
            [self.commentMgr updateShareCommentIsUnNetCompletedWithComment:comment isDel:YES];
            [[CXmppRequestMgr shareInstance] cancelPraiseShareWithCommentId:comment.commentId date:comment.date successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                if ([responseObject[@"result"] isEqualToString:@"success"]) {
                    
                    [self.commentMgr delShareCommentWithCommentId:comment.commentId];
                }
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
        
    } else {
        EFengContent *comment = [[EFengContent alloc] init];
        NSString *timeStamp = [UIUtil getCurrentTimeStamp];
        CServerSettingModel *serverSetting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
        NSString *idkey = serverSetting.yuLiuZiduan1;
        if (M_ISSTRNULL(idkey)) {
            idkey = @"111111";
        }
        NSString *idStr = [NSString stringWithFormat:@"%@%@",timeStamp,idkey];


        comment.shareId = share.share.shareId;
        comment.commentId = idStr;
        comment.yuLiuZiduan2 = 1;
        comment.sendUserId = self.curContact.UserID;
        comment.sendUserName = self.curContact.UserName;
        comment.commentType = @"praise";
        comment.isClick = YES;
        comment.isRead = YES;
        comment.date = timeStamp;
        [self.commentMgr insertWithShareComment:comment];
        
        [[CXmppRequestMgr shareInstance] praiseShareWithSendUserId:self.curContact.UserID commentId:idStr releaseUserId:share.share.releaseUserId contentId:share.share.shareId sendUserName:self.curContact.UserName successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject[@"result"] isEqualToString:@"success"]) {
                [self.commentMgr updateCommentWithCommentId:[NSString stringWithFormat:@"%@",responseObject[@"id"]]
                                                            date:[NSString stringWithFormat:@"%@",responseObject[@"date"]]];
            }
            
            
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
        
    }
    [self loadNewData];
}

- (void)sendMsg:(NSString *)txtMsg
{
    [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
    
    if (M_ISSTRNULL(txtMsg)) {
        return;
    }
    NSString *type = nil;
    NSString *receiveUserId = nil;
    NSString *receiveUserName = nil;
    if (self.shareComment) {
        type = @"reply";
        receiveUserId = self.shareComment.sendUserId;
        receiveUserName = self.shareComment.sendUserName;
    } else {
        type = @"comment";
    }
    EFengShareFrame *shareFrame = self.dataArray.lastObject;
    
    EFengContent *content = [[EFengContent alloc] init];
    content.commentType = type;
    NSString *timeStamp = [UIUtil getCurrentTimeStamp];
    CServerSettingModel *serverSetting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
    NSString *idkey = serverSetting.yuLiuZiduan1;
    if (M_ISSTRNULL(idkey)) {
        idkey = @"111111";
    }
    NSString *idStr = [NSString stringWithFormat:@"%@%@",timeStamp,idkey];

    content.commentId = idStr;
    content.sendUserId = self.curContact.UserID;
    content.sendUserName = self.curContact.UserName;
    content.shareId = shareFrame.share.shareId;
    content.receiveUserId = receiveUserId;
    content.receiveUserName = receiveUserName;
    content.content = txtMsg;
    content.isClick = YES;
    content.isRead = YES;
    content.date = timeStamp;
    content.yuLiuZiduan2 = 1;
    [self.commentMgr insertWithShareComment:content];

    
    [[CXmppRequestMgr shareInstance] composeShareCommentWithShareId:shareFrame.share.shareId commentId:idStr releaseUserId:shareFrame.share.releaseUserId sendUserId:self.curContact.UserID sendUserName:self.curContact.UserName receiveUserId:M_STOREVALUE(receiveUserId) receiveUserName:M_STOREVALUE(receiveUserName) content:txtMsg type:type successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject[@"result"] isEqualToString:@"success"]) {
            [self.commentMgr updateCommentWithCommentId:[NSString stringWithFormat:@"%@",responseObject[@"id"]]
                                                        date:[NSString stringWithFormat:@"%@",responseObject[@"date"]]];
            [USER_DEFAULT setBool:YES forKey:@"sendOK"];
            [USER_DEFAULT synchronize];
        }
        
        
    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    [self loadNewData];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
    
}
- (void)didTap:(UITapGestureRecognizer *)tap
{
    [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
    
}
- (void)EFengShareCommentToolBarDidHiddenEmotionBtn
{
    
}

@end
